# Set this variable to True for debug output
debug = False

import restutils
import xml.dom.minidom
import nirvanixutils
import os
import cgi

secure_services_url = "https://services.nirvanix.com"
services_url = "http://services.nirvanix.com"

class Nirvanix(object):
    def __init__(self,namespace, session):
        self.namespace = namespace
        self.session = session

    def genericFunctionHandler(self,name):
        def handlerFunction(*args,**kwargs):
            # Determine if the connection should be secure
            if args[1]:
                connection = restutils.Connection(secure_services_url);
            else:
                connection = restutils.Connection(services_url);

            # Build parameters based on the passed in associative array
            if (self.session):
                params = 'sessionToken=' + self.session.sessionToken + '&'
            else:
                params = ''

            for key in args[0]:
                params += key + '=' + cgi.escape(args[0][key]) + '&'

            # build the URL of the method to access.
            method_name = '/ws/' + self.namespace + '/' + name + '.ashx'

            # Do the request and get the xml back.
            response_xml = connection.request_post(method_name, params)

            return nirvanixutils.check_response(response_xml)
        return handlerFunction

    def __getattr__(self,name):
        return self.genericFunctionHandler(name)

# This class is used to create the idea of a static method by allowing direct class method calls.
class Session:
    def __init__(self, appKey, username, password):
        # Create a session token on the object.
        self.sessionToken = None
        # create an auth object passing None so we know that this is a special case for the
        # internal session object.
        auth = Nirvanix('Authentication', None)
        # pass login options.
        self.options = {'appKey':appKey,'username':username,'password':password}
        # do a secure login. (Note google states that they will accept ANY secure session and do not
        # care where its from as long as the cert is valid.)
        doc = auth.Login(self.options,True)
        # Get the session token from the xml.
        self.sessionToken = doc.getElementsByTagName("SessionToken")[0].childNodes[0].data
        if debug:
            print "DEBUG: Session() - Session Token=" + self.sessionToken

    def __del__(self):
        # if the object has correctly logged in and assigned a session token then
        # we need to call logout to destroy that session at Nirvanix.
        if self.sessionToken:
            # Create an auth object.
            auth = Nirvanix('Authentication', None)
            #
            logoutOptions = {'sessionToken':self.sessionToken}
            auth.Logout(logoutOptions,True)
            if debug:
                print "DEBUG: Session.__del__ - session destroyed"
